package com.shujia.spark.streaming

import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Durations, StreamingContext}

object Demo2StreamOnRDD {

  def main(args: Array[String]): Unit = {

    val spark: SparkSession = SparkSession
      .builder()
      .appName("stream")
      .master("local[2]")
      .getOrCreate()

    import spark.implicits._
    import org.apache.spark.sql.functions._

    val sc: SparkContext = spark.sparkContext

    /**
      * 创建streaming 上下文对象，指定batch的间隔时间,多久计算一次
      *
      */

    val ssc = new StreamingContext(sc,Durations.seconds(5))

    //累加1
    ssc.checkpoint("data/checkpoint1")

    val linesDS: ReceiverInputDStream[String] = ssc.socketTextStream("master",8888)



    /**
      * transform: 将ds 转换成rdd ，再将rdd转换成ds
      *
      */

    val linesDS2: DStream[(String, Int)] = linesDS.transform(rdd =>{

      /**
        * 每个batch计算一次
        */

      val rddToDS: RDD[(String, Int)] = rdd
        .flatMap(_.split(","))
        .map((_,1))
        .reduceByKey(_ + _)
        //.foreach(println)

      val lineDF: DataFrame = rdd.toDF("lines")

      lineDF.select(explode(split($"lines",",")) as "word")
        .groupBy($"word")
        .agg(count($"word") as "C")
        //.show()

      lineDF.createOrReplaceTempView("words")

      spark.sql(
        """
          |select word,count(1) as wordCount from(
          |select explode(split(lines,',')) as word from words
          |) as a
          |group by word
          |
        """.stripMargin)
        //.show()

      //返回一个新的rdd
      rddToDS
    })

    /**
      * foreachRDD: 将DS 转换成RDD来使用，可以使用rdd的api
      *
      */
    /*linesDS.foreachRDD(rdd =>{
    rdd
      .flatMap(_.split(","))
      .map((_,1))
      .reduceByKey(_ + _)
    //.foreach(println)

    val lineDF: DataFrame = rdd.toDF("lines")

    lineDF.select(explode(split($"lines",",")) as "word")
      .groupBy($"word")
      .agg(count($"word") as "C")
    //.show()

    lineDF.createOrReplaceTempView("words")

    spark.sql(
      """
        |select word,count(1) as wordCount from(
        |select explode(split(lines,',')) as word from words
        |) as a
        |group by word
        |
        """.stripMargin)
    //.show()
  })*/

    //累加2
    def updateFun(seq: Seq[Int],option: Option[Int]):Option[Int] ={

      //计算当前batch单词的数量
      val currentCount: Int = seq.sum

      //获取之前单词的数量
      val lastCount: Int = option.getOrElse(0)

      //返回最新单词的数量
      Some(currentCount + lastCount)
    }

    val countDS: DStream[(String, Int)] = linesDS2.updateStateByKey(updateFun)

    countDS.print()


    //启动spark streaming
    ssc.start()
    ssc.awaitTermination()
    ssc.stop()

  }

}
